const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verify = require('../../auth/verify')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')

/**
 * @description 删除文章
 */
module.exports = function () {
    const that = this
    const query = this.getQueryData(this.request.url)
    /**
     * @description 授权
     */
    const authorization = this.request.headers.authorization
    verifyRequestMethod(this.request, 'GET').then(function () {
        /**
         * @description 授权验证
         */
        if (that.isDef(authorization)) {
            return verify(authorization)
        } else {
            return Promise.reject(new Error('缺少Authorization！'))
        }
    }).then(function (data) {
        if (!isNaN(parseInt(query.articleId))) {
            return Promise.resolve(data)
        } else {
            return Promise.reject(new Error('无效的文章Id！'))
        }
    }).then(function (data) {
        return dataBase.connect(sql.SQL_SELECT_ARTICLE_AUTHOR_ID_ONE(data.username, query.articleId))
    }).then(function (result) {
        if (that.isDef(result[0])) {
            return Promise.resolve(result[0])
        } else {
            return Promise.reject(new Error('无效的文章Id，或文章处于审核状态，无法操作，请联系管理员！'))
        }
    }).then(function (data) {
        return dataBase.connect(sql.SQL_DELETE_ARTICLE_ONE(data.authorId, data.articleId)).then(function () {
            return Promise.resolve(data)
        })
    }).then(function (data) {
        return dataBase.connect(sql.SQL_DELETE_ARTICLE_CONTENT_ONE(data.articleId)).then(function () {
            return Promise.resolve(data)
        })
    }).then(function (data) {
        return dataBase.connect(sql.SQL_UPDATE_USER_COLLECTIONS_ID(data.articleId)).then(function () {
            return Promise.resolve(data)
        })
    }).then(function (data) {
        return dataBase.connect(sql.SQL_UPDATE_USER_COLLECTIONS_OTHER(data.articleId))
    }).then(function () {
        that.response.outPrintData({}, '删除成功！')
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}